package cn.bonoon.kernel.web.html.form;

import cn.bonoon.kernel.util.AlignType;
import cn.bonoon.kernel.web.html.FormSetting;
import cn.bonoon.kernel.web.html.UIPropertyBuilder;
/**
 * <pre>
 * 需要更新的地方：
 * 1.允许任意的cell以新行开始，如果以新行开始，并且当前行没有结束，后面以&lt;td colspan='?'&gt;来结束掉
 * 2.允许某个cell独占一行，这种方式则头也是独占一行，这种方式需要第1点的支持
 * </pre>
 * @author jackson
 *
 * @param <F>
 */
public abstract class AbstractPropertyParser<F extends FormSetting> implements PropertyParser {
	
	protected static int fontSize = 12;
	protected static int imageSize = 18;
	
	protected String name;
	protected int ordinal = 0;
	protected int colspan = 0;
	protected int rowspan = 0;
	protected int height = 0;
	protected int width = 0;
	protected int realWidth = 0;
	protected boolean showHead = true;
	protected AlignType align;
	
	protected final F formParser;

	protected AbstractPropertyParser(F formParser) {
		this.formParser = formParser;
	}
	
	@Override
	public int colspan() {
		return colspan;
	}
	
	@Override
	public int rowspan() {
		return rowspan;
	}
	
	@Override
	public int compareTo(PropertyParser o) {
		return ordinal - o.ordinal();
	}
	
	@Override
	public int ordinal() {
		return ordinal;
	}

	protected StringBuilder buildHead(StringBuilder html) {
		return html.append(name);
	}

	protected abstract void buildContent(UIPropertyBuilder pb)throws Exception;

	protected void buildContented(UIPropertyBuilder pb) { }

	public void parseCell(UIPropertyBuilder pb, int column, int index) throws Exception{
		StringBuilder html = pb.getInitHtml();
		int colspan = column - index - 1, tdColspan;
		if(0 <= this.colspan){
			colspan = Math.min(this.colspan, colspan);
		}
		if (showHead) {
			if (colspan > 0){
				tdColspan = (colspan * 2) + 1;
			}else{
				tdColspan = 0;
			}
			int hw = formParser.getHeadWidth();
			html.append("<th style='width:").append(hw).append("px;'");
			if (rowspan > 0) 
				html.append(" rowspan='").append((rowspan + 1)).append('\'');
			buildHead(html.append('>')).append("：</th>");
		} else{
			realWidth += formParser.getHeadWidth();
			if(colspan > 0){
				tdColspan = (colspan * 2) + 2;
			}else{
				tdColspan = 2;
			}
		}
		html.append("<td style='width:").append(realWidth).append("px;");
		if (height > 0)  // 有待处理
			html.append("vertical-align:top;height:").append(height).append("px;");
		if (null != align && align != AlignType.NONE)
			html.append("text-align:").append(align.getAlign()).append(';');
		if (tdColspan > 0) 
			html.append("' colspan='").append(tdColspan);
		if (rowspan > 0) 
			html.append("' rowspan='").append((rowspan + 1));
		html.append("'>");
		buildContent(pb);
		buildContented(pb);
		html.append("</td>");
	}
}
